#############################################################
# File: solve.py
# Function: Solves equation system of the type Ax=b using mainly multigrid methods provenient
# from the pyAMG package (http://code.google.com/p/pyamg/)
# Author: Bruno Luna
# Date: 03/02/11
# Modifications Date:
# 
#
#
#
#
#############################################################
from scipy.sparse import csr_matrix
from pyamg import smoothed_aggregation_solver

def solve_eq_system(A, rhs):
    """Solves the equation system with pyAMG.""" 
    
    # Get sparse matrix data
    (row,col,data) = A.data()
    n = A.size(0)
    Asp = csr_matrix( (data,col.view(),row.view()), shape=(n,n))
    
    # Get right-hand side vector(rhs) data
    b = rhs.data()
    
    # Solves equation system
    ml = smoothed_aggregation_solver(Asp,max_coarse=10)
    residuals = []
    x = ml.solve(b,tol=1e-10,accel="gmres",residuals=residuals)
    
    # Print residuals history
    residuals = residuals/residuals[0]
    print ml
    print residuals
    
    return x,  residuals
############################################################
